package main

import (
	"io"
	"log"

	"github.com/jacobsa/go-serial/serial"
)

func openSerialPort(com string, rate uint) io.ReadWriteCloser {
	options := serial.OpenOptions{
		PortName:        com,
		BaudRate:        rate,
		DataBits:        8,
		StopBits:        1,
		MinimumReadSize: 4,
	}
	port, err := serial.Open(options)
	if err != nil {
		log.Fatalf("serial.Open: %v", err)
	}
	return port
}

func serialPortWriteString(port io.ReadWriteCloser, s string) {
	_, err := port.Write([]byte(s))
	if err != nil {
		log.Fatalf("port.Write: %v", err)
	}
}

func serialPortReadString(port io.ReadWriteCloser) string {
	s := make([]byte, 128)
	n, err := port.Read(s)
	if err != nil {
		log.Fatalf("port.Read: %v", err)
	}
	return string(s[:n])
}

func main() {
	ch := make(chan string)
	port := openSerialPort("COM5", 115200)
	defer port.Close()
	serialPortWriteString(port, "hello, world")

	go func(port io.ReadWriteCloser) {
		for {
			ret := serialPortReadString(port)
			if ret == "" {
				continue
			}
			ch <- ret
		}
	}(port)
	for {
		log.Printf("%s", <-ch)
	}
}
